package com.example.websocket;

import com.alibaba.fastjson.JSONObject;
import com.example.constant.CustomSEnum;
import com.example.pojo.dto.CustomSDTO;
import com.example.pojo.vo.MessageVo;
import com.example.tools.RedisTools;
import com.example.tools.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: hualao
 * @Version: 0.0.1V
 * @Date: 2018/12/19
 * @Description: 服务端
 **/
@Slf4j
@Component
@ServerEndpoint("/websocketServer/{username}")
public class WebSocketServer {

    private StringRedisTemplate stringRedisTemplate = SpringUtils.getBean(StringRedisTemplate.class);

    /**
     * 以用户的姓名为key，WebSocket为对象保存起来
     */
    private static Map<String, WebSocketServer> clients = new ConcurrentHashMap<>();

    /**
     * 会话
     */
    private Session session;

    /**
     * 用户名
     */
    private String username;

    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        log.info("登录用户会话 --> {}", session);
        log.info("登录用户名称 --> {}", username);
        this.username = username;
        this.session = session;
        clients.put(username, this);

        if (!RedisTools.existsHash(stringRedisTemplate, CustomSEnum.CUSTOM_S_LIST.getKey(), username)) {
            CustomSDTO customSDTO = new CustomSDTO();
            customSDTO.setNumber(0);
            customSDTO.setServer(username);
            RedisTools.hset(stringRedisTemplate, CustomSEnum.CUSTOM_S_LIST.getKey(), username, JSONObject.toJSONString(customSDTO));
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info("服务端发生了错误" + error.getMessage());
    }

    @OnClose
    public void onClose() {
        log.info("关闭会话 --> {}", username);
        clients.remove(username);
        if (RedisTools.existsHash(stringRedisTemplate, CustomSEnum.CUSTOM_S_LIST.getKey(), username)){
            RedisTools.hdel(stringRedisTemplate,CustomSEnum.CUSTOM_S_LIST.getKey(),username);
        }
        log.info("线上用户 --> {}", clients);
    }

    public void sendMessageToServer(MessageVo messageVo) throws IOException {
        for (WebSocketServer item : clients.values()) {
            if (item.username.equals(messageVo.getServer())) {
                item.session.getAsyncRemote().sendText(JSONObject.toJSONString(messageVo));
                break;
            }
        }
    }

}
